package library.and.xps.com.step.view.activity;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.google.gson.Gson;
import com.jude.utils.JUtils;
import com.orhanobut.logger.Logger;
import com.squareup.okhttp.Request;
import com.zhy.autolayout.AutoLinearLayout;

import org.greenrobot.eventbus.EventBus;

import jp.wasabeef.glide.transformations.CropCircleTransformation;
import library.and.xps.com.step.EventBusCommond;
import library.and.xps.com.step.R;
import library.and.xps.com.step.SPConstant;
import library.and.xps.com.step.URLConstants;
import library.and.xps.com.step.m.model.PkDetail;
import library.and.xps.com.step.m.model.RequestParams;
import library.and.xps.com.step.m.netapi.OkHttpClientUtils;
import library.and.xps.com.step.net.ResponceWrapper;
import library.and.xps.com.step.util.HttpResponsHelper;
import library.and.xps.com.step.util.RequestCallback;
import library.and.xps.com.step.view.base.BaseActivity;

public class PersonalChallengeDetailActivity extends BaseActivity {
    TextView tv_challenger_name, tv_bechallenger_name, tv_challenger_exc, tv_bechallenger_exc, tv_chips, tv_date, tv_read_time, tv_state;
    ImageView iv_challenger_header, iv_bechallenger_header, iv_back;
    AutoLinearLayout al_change_pk_state;
    TextView tv_reject, tv_agree, tv_d_cancel_pk,tv_reading_time;
    int pkid = 0;

    @Override
    protected int getLayout() {
        return R.layout.activity_challenge_detail;
    }

    @Override
    protected void setData() {
        Intent i = getIntent();
        pkid = i.getIntExtra("pkid", 0);
        if (pkid == 0) return;
        request(pkid);
    }

    void refreshdata(PkDetail pkdetail) {

        setupCircleImg(this, iv_bechallenger_header, pkdetail.getObj().getBico());
        setupCircleImg(this, iv_challenger_header, pkdetail.getObj().getCico());

        tv_bechallenger_exc.setText(pkdetail.getObj().getBsteps() + "");
        tv_challenger_exc.setText(pkdetail.getObj().getSteps() + "");
        tv_read_time.setText(pkdetail.getObj().getReadingtimes() + "");
        tv_reading_time.setText(pkdetail.getObj().getReadingtimes() + "人正在围观");
        if (pkdetail.getObj().getChallenger() == Integer.valueOf(getUser().getUserid())) {
            al_change_pk_state.setVisibility(View.GONE);
            tv_d_cancel_pk.setVisibility(View.VISIBLE);
        } else {
            al_change_pk_state.setVisibility(View.VISIBLE);
            tv_d_cancel_pk.setVisibility(View.GONE);
        }

        if (pkdetail.getObj().getState() == 2||pkdetail.getObj().getState() == 1) {
            al_change_pk_state.setVisibility(View.GONE);
            tv_d_cancel_pk.setVisibility(View.GONE);
        }

        tv_chips.setText(pkdetail.getObj().getChip());
        tv_date.setText(pkdetail.getObj().getStarttime() + "\n" + pkdetail.getObj().getEndtime());

    }

    void request(int pkId) {
        String data = URLConstants.PERSONACTIVE.GETSElFPKBYPKID + "?pkid=" + pkId;
        OkHttpClientUtils.getDataAsync(this, data, new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                Logger.d(response.getBody(), "PersonalChallengeDetailActivity");

                if (HttpResponsHelper.SuccessResponce(response)) {
                    PkDetail data = new Gson().fromJson(response.getBody(), PkDetail.class);
                    refreshdata(data);
                }
            }

            @Override
            public void onStart() {

            }
        }, "");
    }

    public void setupCircleImg(Context context, ImageView imageView, String url) {
        if ("null".equals(url) || "NULL".equals(url) || TextUtils.isEmpty(url)) return;

        String imgUrl = URLConstants.FILE.FileDownload + url;

        GlideUrl glideUrl = new GlideUrl(imgUrl, new LazyHeaders.Builder()
                .addHeader("token", JUtils.getSharedPreference().getString(SPConstant.USER_TOKEN, ""))
                .build());

        Glide.with(context).load(glideUrl)
                .placeholder(R.drawable.default_header_male)
                .bitmapTransform(new CropCircleTransformation(context))
                .into(imageView);
    }

    @Override
    protected void init() {
        tv_challenger_name = r2v(R.id.tv_challenger_name);
        tv_bechallenger_name = r2v(R.id.tv_bechallenger_name);
        tv_challenger_exc = r2v(R.id.tv_challenger_exc);
        tv_bechallenger_exc = r2v(R.id.tv_bechallenger_exc);
        al_change_pk_state = r2v(R.id.al_change_pk_state);
        tv_reading_time = r2v(R.id.tv_reading_time);
        tv_agree = r2v(R.id.tv_agree);
        tv_agree.setOnClickListener(this);
        tv_reject = r2v(R.id.tv_reject);
        tv_reject.setOnClickListener(this);
        tv_d_cancel_pk = r2v(R.id.tv_d_cancel_pk);
        tv_d_cancel_pk.setOnClickListener(this);

        tv_chips = r2v(R.id.tv_chips);
        tv_date = r2v(R.id.tv_date);
        tv_state = r2v(R.id.tv_cancel_pk);
        tv_read_time = r2v(R.id.tv_read_time);
        iv_challenger_header = r2v(R.id.iv_challenger_header);
        iv_bechallenger_header = r2v(R.id.iv_bechallenger_header);
        iv_back = r2v(R.id.actionbar_iv_back);
        iv_back.setOnClickListener(this);

        ((TextView) r2v(R.id.actionbar_tv_title)).setText("挑战详情");
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.actionbar_iv_back:
                finish();
                EventBus.getDefault().post(EventBusCommond.FREASH_PERSON_CHALLENGE);
                break;
            case R.id.tv_d_cancel_pk:
                modifyChallengeState("state", "-1");//取消pk
                break;
            case R.id.tv_reject:
                modifyChallengeState("state", "3");//拒绝pk
                break;
            case R.id.tv_agree:
                modifyChallengeState("state", "5");//同意pk
                break;
        }
    }

    void modifyChallengeState(final String param, final String value) {
        String json = "";
        if (param.equals("readingtimes")) {
            json = RequestParams.getNewInstance().setUserid(getUser().getUserid())
                    .setPkids(pkid+"")
                    .setReadingtimes(value)
                    .getJson()
                    .toString();
        } else if (param.equals("state")) {
            json = RequestParams.getNewInstance()
                    .setUserid(getUser().getUserid())
                    .setPkids(pkid+"")
                    .setState(value)
                    .getJson()
                    .toString();
        }

        OkHttpClientUtils.postJsonStringAsync(this, URLConstants.PERSONACTIVE.UPDATEUSERPK, json, new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                dissmisDialog();
                if (e instanceof RuntimeException) {
                    JUtils.Toast(e.getMessage());
                }
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                dissmisDialog();
                if (HttpResponsHelper.SuccessResponce(response)) {
                    if ("state".equals(param)) {//判断 在为修改状态的请求时 做相应的操作
                        afterStateChange(value);
                    }

                } else {
                    JUtils.Toast("修改失败");
                }
            }

            @Override
            public void onStart() {
                showDialog();
            }
        }, "");
    }

    void afterStateChange(String value) {
        if ("-1".equals(value)) {
            finish();
            EventBus.getDefault().post(EventBusCommond.FREASH_PERSON_CHALLENGE);
        } else if ("3".equals(value)) {
            finish();
            EventBus.getDefault().post(EventBusCommond.FREASH_PERSON_CHALLENGE);
        } else if ("5".equals(value)) {
            request(pkid);
        }
    }

}
